package com.ebring.shareEducation.service.impl;

import com.ebring.shareEducation.bean.User;
import com.ebring.shareEducation.bean.UserInfo;
import com.ebring.shareEducation.bean.UserRole;
import com.ebring.shareEducation.bean.response.UserRsp;
import com.ebring.shareEducation.dao.UserInfoMapper;
import com.ebring.shareEducation.dao.UserMapper;
import com.ebring.shareEducation.dao.UserRoleMapper;
import com.ebring.shareEducation.dao.UserRspMapper;
import com.ebring.shareEducation.service.UserService;
import com.ebring.shareEducation.utils.*;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserRspMapper userRspMapper;



    @Autowired
    private UserRoleMapper userRoleMapper;

    // 新增用户
    @Override
    public RspMsg<User> insertUser(User user) {
        RspMsg rspMsg = new RspMsg();
        user.setUserId(UuidUtils.getNumberId(6));
        String userId = user.getUserId();
        user.setPassword("111111");
        user.setSalt(UUID.randomUUID().toString().replaceAll("-", ""));
        user.setPassword(Md5Utils.encryptPassword(user.getPassword(), user.getSalt()));

        int i = userMapper.insertSelective(user);

        if (i > 0) {
            if (!StringUtils.isEmpty(user.getPost())) {
                UserRole userRole = new UserRole();
                userRole.setId(UuidUtils.getUUID());
                userRole.setUserId(userId);
                userRole.setRoleId(user.getPost());
                int i1 = userRoleMapper.insertSelective(userRole);
            }
        }

        if (i == 0) {
            rspMsg.setError();
            rspMsg.setMsg("插入失败");
            return rspMsg;
        }

        rspMsg.setOK();
        rspMsg.setMsg("数据插入成功");
        return rspMsg;
    }

    // 更新用户
    @Override
    public RspMsg<User> updateUser(User user) {
        RspMsg rspMsg = new RspMsg();
        User user1 = userMapper.selectByPrimaryKey(user.getUserId());


        if (user1.getPassword().equals(user.getPassword())) {
            user.setPassword(user.getPassword());
        } else {
            user.setPassword(user.getPassword());
            // 将新密码生成盐值并且加密
            user.setSalt(UUID.randomUUID().toString().replaceAll("-", ""));
            user.setPassword(Md5Utils.encryptPassword(user.getPassword(), user.getSalt()));
        }

        int i = userMapper.updateByPrimaryKeySelective(user);
        if (i == 0) {
            rspMsg.setError();
            rspMsg.setMsg("更新信息失败");
            return rspMsg;
        }
        rspMsg.setOK();
        return rspMsg;
    }

    //查询审核未通过的人
    @Override
    public RspMsg<List<User>> selectByExaminationState(String phone, String examinationState) {
        RspMsg rspMsg = new RspMsg();
        Map<String, Object> map = new LinkedHashMap<>();
        Example example = new Example(User.class);
        if ((phone != null && !"".equals(phone)) && (examinationState != null && !"".equals(examinationState))) {
            example.createCriteria().andLike("phone", "%" + phone + "%").andLike("examinationState", "%" + examinationState + "%");
        }
        if (phone != null && !"".equals(phone)) {
            example.createCriteria().andLike("phone", "%" + phone + "%");
        }
        if (examinationState != null && !"".equals(examinationState)) {
            example.createCriteria().andLike("examinationState", "%" + examinationState + "%");
        }
        List<User> userList = userMapper.selectByExample(example);
        if (userList.isEmpty() || userList == null) {
            rspMsg.setOK();
            rspMsg.setMsg("未找到数据");
            return rspMsg;
        }
        PageInfo<User> pageInfo = new PageInfo<>(userList);
        // 总条数
        map.put("total", pageInfo.getTotal());
        // 每页显示条数
        map.put("curPage", pageInfo.getPageSize());
        // 总页数
        map.put("pages", pageInfo.getPages());
        // 当前页
        map.put("pageNum", pageInfo.getPageNum());
        map.put("userList", userList);
        rspMsg.setOK();
        rspMsg.setResult(map);
        return rspMsg;
    }

    @Override
    public RspMsg<UserRsp> selectUsersfind(){
        RspMsg rspMsg = new RspMsg();
        Map<String, Object> map = new LinkedHashMap<>();
        List<UserRsp> userList =userRspMapper.findUsers();
        if (userList.isEmpty() || userList == null) {
            rspMsg.setOK();
            rspMsg.setMsg("未找到相关数据");
            return rspMsg;
        }

        PageInfo<UserRsp> pageInfo = new PageInfo<UserRsp>(userList);
        // 总条数
        map.put("total", pageInfo.getTotal());
        // 每页显示条数
        map.put("curPage", pageInfo.getPageSize());
        // 总页数
        map.put("pages", pageInfo.getPages());
        // 当前页
        map.put("pageNum", pageInfo.getPageNum());
        map.put("userList", userList);
        rspMsg.setOK();
        rspMsg.setResult(map);
        return rspMsg;
    }

    // 根据ID查找用户
    @Override
    public RspMsg<User> selectUserByUserId(String userId) {
        RspMsg<User> rspMsg = new RspMsg<>();
        User user = userMapper.selectByPrimaryKey(userId);
        if (StringUtils.isEmpty(user)) {
            rspMsg.setError();
            rspMsg.setMsg("未找到数据");
            return rspMsg;
        }
        rspMsg.setOK();
        rspMsg.setResult(user);
        return rspMsg;
    }

    // 批量删除用户
    @Override
    public RspMsg<User> DeleteUsers(String[] userId) {

        RspMsg rspMsg = new RspMsg();
        int sum = 0;
        for (String s : userId) {
            userMapper.deleteByPrimaryKey(s);
            userRoleMapper.deletes(s);
            sum++;
        }

        if (sum > 0) {
            rspMsg.setOK();
            rspMsg.setResult(sum);
            return rspMsg;
        }

        rspMsg.setError();
        rspMsg.setMsg("删除失败");
        return rspMsg;
    }

    // 用户登陆
    @Override
    public RspMsg<User> login(String userId, String password) {
        RspMsg rspMsg = new RspMsg();
        Map<String, Object> map = new LinkedHashMap<>();
        if (null == userId || "".equals(userId)) {
            rspMsg.setError();
            rspMsg.setMsg("用户名不能为空");
            return rspMsg;
        }
        User user = userMapper.selectByPrimaryKey(userId);
        if (user == null) {
            rspMsg.setError();
            rspMsg.setMsg("该用户不存在");
            return rspMsg;
        } else if (!Md5Utils.encryptPassword(password, user.getSalt()).equals(user.getPassword())) {
            rspMsg.setError();
            rspMsg.setMsg("密码不正确");
            return rspMsg;
        } else {

            // 判断密码有效期是否超时
            String validdate = user.getValiddate();
            Date currentTime = new Date();
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            ParsePosition pos = new ParsePosition(0);
            Date strtodate = formatter.parse(validdate, pos);
            int i = strtodate.compareTo(currentTime);
            if (i == 1) {
                String token = JwtUtils.sign(user, 30L * 24L * 3600L * 1000L);
                if (token != null) {
                    map.put("data", user);
                    map.put("token", token);
                    rspMsg.setOK();
                    rspMsg.setResult(map);
                    return rspMsg;
                }
            }
            rspMsg.setError();
            rspMsg.setMsg("当前用户密码有效期已过，建议更改密码重新登录");
            return rspMsg;
        }

    }

    // 修改密码
    @Override
    public RspMsg<User> changePassword(String oldPassword, String newPassword, String validDate, String token) {
        RspMsg rspMsg = new RspMsg();
        Map<String, Object> map = new HashMap<>();
        if (token == null || "".equals(token)) {
            rspMsg.setError();
            rspMsg.setMsg("用户未登陆,请先登录");
            return rspMsg;
        }
        User user = JwtUtils.unsign(token, User.class);
        if (!Md5Utils.encryptPassword(oldPassword, user.getSalt()).equals(user.getPassword())) {
            rspMsg.setError();
            rspMsg.setMsg("原密码错误,请重新输入");
            return rspMsg;
        } else {
            user.setPassword(newPassword);
            // 将新密码生成盐值并且加密
            user.setSalt(UUID.randomUUID().toString().replaceAll("-", ""));
            user.setPassword(Md5Utils.encryptPassword(user.getPassword(), user.getSalt()));
            user.setValiddate(validDate);
            int i = userMapper.updateByPrimaryKeySelective(user);
            if (i == 0) {
                rspMsg.setError();
                rspMsg.setMsg("密码修改失败");
                return rspMsg;
            }
            rspMsg.setOK();
            rspMsg.setMsg("密码修改成功");
            return rspMsg;
        }

    }

    // 查询所有用户
    @Override
    public RspMsg<UserRsp> findUserByuserId(String userId) {
        RspMsg rspMsg = new RspMsg();
        Map<String, Object> map = new LinkedHashMap<>();
        List<UserRsp> userList = userRspMapper.findUserByuserId(userId);
        if (userList.isEmpty() || userList == null) {
            rspMsg.setOK();
            rspMsg.setMsg("未找到相关数据");
            return rspMsg;
        }

        PageInfo<UserRsp> pageInfo = new PageInfo<>(userList);
        // 总条数
        map.put("total", pageInfo.getTotal());
        // 每页显示条数
        map.put("curPage", pageInfo.getPageSize());
        // 总页数
        map.put("pages", pageInfo.getPages());
        // 当前页
        map.put("pageNum", pageInfo.getPageNum());
        map.put("userList", userList);
        rspMsg.setOK();
        rspMsg.setResult(map);
        return rspMsg;
    }


    // 查询所有用户
    @Override
    public RspMsg<UserRsp> selectUsers(String userId, String username, String branchId, String institutionName) {
        RspMsg rspMsg = new RspMsg();
        Map<String, Object> map = new LinkedHashMap<>();
        List<UserRsp> userList = userRspMapper.selectUsers(userId, branchId, username, institutionName);
        if (userList.isEmpty() || userList == null) {
            rspMsg.setOK();
            rspMsg.setMsg("未找到相关数据");
            return rspMsg;
        }

        PageInfo<UserRsp> pageInfo = new PageInfo<>(userList);
        // 总条数
        map.put("total", pageInfo.getTotal());
        // 每页显示条数
        map.put("curPage", pageInfo.getPageSize());
        // 总页数
        map.put("pages", pageInfo.getPages());
        // 当前页
        map.put("pageNum", pageInfo.getPageNum());
        map.put("userList", userList);
        rspMsg.setOK();
        rspMsg.setResult(map);
        return rspMsg;
    }


    // 根据多条件查找用户
    @Override
    public RspMsg<List<UserRsp>> findUser(UserRsp userRsp) {
        RspMsg rspMsg = new RspMsg();
        Map<String, Object> map = new LinkedHashMap<>();
        List<UserRsp> userList = userRspMapper.findUser(userRsp);
        if (userList.isEmpty() || userList == null) {
            rspMsg.setOK();
            rspMsg.setMsg("未找到相关用户");
            return rspMsg;
        }

        PageInfo<UserRsp> pageInfo = new PageInfo<>(userList);

        // 总条数
        map.put("total", pageInfo.getTotal());
        // 每页显示条数
        map.put("curPage", pageInfo.getPageSize());
        // 总页数
        map.put("pages", pageInfo.getPages());
        // 当前页
        map.put("pageNum", pageInfo.getPageNum());
        map.put("userList", userList);
        rspMsg.setOK();
        rspMsg.setResult(map);
        return rspMsg;

    }

    // 修改密码（忘记密码）
    @Override
    public RspMsg<User> forgetPassword(String userId) {
        RspMsg rspMsg = new RspMsg();
        User user = new User();
        user.setUserId(userId);
        user.setPassword("111111");
        user.setSalt(UUID.randomUUID().toString().replaceAll("-", ""));
        user.setPassword(Md5Utils.encryptPassword(user.getPassword(), user.getSalt()));
        int i = userMapper.updateByPrimaryKeySelective(user);
        if (i > 0) {
            rspMsg.setOK();
            return rspMsg;
        }

        rspMsg.setError();
        rspMsg.setMsg("密码重置失败");
        return rspMsg;
    }

    // 修改密码（忘记密码）
    @Override
    public RspMsg<User> forgetphone(String userId, String phone) {
        RspMsg rspMsg = new RspMsg();
        User user = new User();
        user.setUserId(userId);
        user.setPhone(phone);
        int i = userMapper.updateByPrimaryKeySelective(user);
        if (i > 0) {
            rspMsg.setOK();
            return rspMsg;
        }
        rspMsg.setError();
        rspMsg.setMsg("手机号码修改失败");
        return rspMsg;
    }



    //注销账号
    @Override
    public RspMsg<User> cancelUser(String userId) {
        RspMsg rspMsg = new RspMsg();
        User user = userMapper.selectByPrimaryKey(userId);
        if (user == null) {
            rspMsg.setOK();
            rspMsg.setMsg("当前用户不存在");
            return rspMsg;
        }
        user.setState("0");
        int i = userMapper.updateByPrimaryKeySelective(user);
        if (i > 0) {
            rspMsg.setOK();
            rspMsg.setMsg("注销成功");
            return rspMsg;
        }
        rspMsg.setError();
        rspMsg.setMsg("注销失败");
        return rspMsg;
    }

    /**
     * 修改登录密码
     *
     * @param userId
     * @param oldPassword
     * @param newPassword
     * @return
     */
    @Override
    public RspMsg updatePassword(String userId, String oldPassword, String newPassword) {
        RspMsg rspMsg = new RspMsg();
        if (oldPassword.trim().equals(newPassword.trim())) {
            rspMsg.setError();
            rspMsg.setMsg("新密码与旧密码重复，请重新输入!");
            return rspMsg;
        }
        User user = userMapper.selectByPrimaryKey(userId);
        String oldPassword1 = Md5Utils.encryptPassword(oldPassword, user.getSalt());
        System.out.println(oldPassword1);
        if (!oldPassword1.equals(user.getPassword())) {
            rspMsg.setError();
            rspMsg.setMsg("原密码错误,请重新输入");
            return rspMsg;
        } else {
            user.setPassword(newPassword);
            // 将新密码生成盐值并且加密
            user.setSalt(UUID.randomUUID().toString().replaceAll("-", ""));
            user.setPassword(Md5Utils.encryptPassword(user.getPassword(), user.getSalt()));
            int i = userMapper.updateByPrimaryKeySelective(user);
            if (i == 0) {
                rspMsg.setError();
                rspMsg.setMsg("密码修改失败");
                return rspMsg;
            }
            rspMsg.setOK();
            rspMsg.setMsg("密码修改成功");
            return rspMsg;
        }
    }

    //新增支付密码
    @Override
    public RspMsg addPayPassword(String payPassWord, String userId) {
        RspMsg rspMsg = new RspMsg();
        User user = new User();
        //新增支付密码
        user.setSalt(UUID.randomUUID().toString().replaceAll("-", ""));
        user.setPayPassword(Md5Utils.encryptPassword(payPassWord, user.getSalt()));
        user.setUserId(userId);
        int i = userMapper.updateByPrimaryKeySelective(user);
        if (i > 0) {
            rspMsg.setOK();
            rspMsg.setMsg("新增加支付密码成功");
            return rspMsg;
        }
        return rspMsg;
    }

    /**
     * 修改支付密码
     *
     * @param userId
     * @param oldPayPassword
     * @param newPayPassword
     * @return
     */
    @Override
    public RspMsg updatePayPassword(String userId, String oldPayPassword, String newPayPassword) {
        RspMsg rspMsg = new RspMsg();
        if (oldPayPassword.trim().equals(newPayPassword.trim())) {
            rspMsg.setError();
            rspMsg.setMsg("新密码与旧密码重复，请重新输入!");
            return rspMsg;
        }
        User user = userMapper.selectByPrimaryKey(userId);
        if (!Md5Utils.encryptPassword(oldPayPassword, user.getSalt()).equals(user.getPayPassword())) {
            rspMsg.setError();
            rspMsg.setMsg("原密码错误,请重新输入");
            return rspMsg;
        } else {
            user.setPassword(newPayPassword);
            // 将新密码生成盐值并且加密
            user.setSalt(UUID.randomUUID().toString().replaceAll("-", ""));
            user.setPassword(Md5Utils.encryptPassword(user.getPayPassword(), user.getSalt()));
            int i = userMapper.updateByPrimaryKeySelective(user);
            if (i == 0) {
                rspMsg.setError();
                rspMsg.setMsg("密码修改失败");
                return rspMsg;
            }
            rspMsg.setOK();
            rspMsg.setMsg("密码修改成功");
            return rspMsg;
        }
    }

    @Override
    public RspMsg authId(User user) {
        RspMsg rspMsg = new RspMsg();
        int i = userMapper.updateByPrimaryKeySelective(user);
        if (i > 0) {
            rspMsg.setOK();
            rspMsg.setMsg("身份认证成功!");
        } else {
            rspMsg.setError();
            rspMsg.setMsg("身份认证失败!");
        }
        return rspMsg;
    }

    /**
     * 充值金币
     *
     * @return
     */
    @Override
    public RspMsg addPayGold(String userId, String payGold) {
        RspMsg rspMsg = new RspMsg();
        User user = userMapper.selectByPrimaryKey(userId);
        Integer paygold = Integer.parseInt(user.getPayGold()) + Integer.parseInt(payGold);
        user.setPayGold(Integer.toString(paygold));
        int i = userMapper.updateByPrimaryKeySelective(user);
        if (i == 0) {
            rspMsg.setError();
            rspMsg.setMsg("充值失败");
            return rspMsg;
        }
        rspMsg.setOK();
        rspMsg.setMsg("充值成功");
        return rspMsg;
    }

    // 更新用户
    @Override
    public RspMsg<User> auditUser(String userId, String examinationState) {
        RspMsg rspMsg = new RspMsg();
        User user = userMapper.selectByPrimaryKey(userId);
        user.setExaminationState(examinationState);
        int i = userMapper.updateByPrimaryKeySelective(user);
        if (i == 0) {
            rspMsg.setError();
            rspMsg.setMsg("更新信息失败");
            return rspMsg;
        }
        rspMsg.setOK();
        rspMsg.setMsg("更新信息成功");
        return rspMsg;
    }

    @Override
    public int updateUserByEntity(User user) {
        int i = userMapper.updateByPrimaryKeySelective(user);
        return i;
    }

    @Override
    public User selectUserBeanByUserId(String userId) {
        Example example = new Example(User.class);
        example.or().andEqualTo("userId",userId);
        List<User> users = userMapper.selectByExample(example);
        if(users.size()>0){
            return users.get(0);
        }else{
            return null;
        }
    }

}
